package by.koleda.benicetobunnies.service;

import by.koleda.benicetobunnies.helper.ParamCallback;
import by.koleda.benicetobunnies.manager.ContentManager;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class BarcodeService extends Service implements ParamCallback<String> {
	
	public static final String EXTRA_KEY_MESSAGE = "message";
	
	public static final String ACTION_ON_ERROR = "by.koleda.benicetobunnies.service.BARCODE_SERVICE_ACTION_ON_ERROR";
	
	public static final String ACTION_ON_SUCCESS = "by.koleda.benicetobunnies.service.BARCODE_SERVICE_ACTION_ON_SUCCESS";
	
	public static final String BARCODE_TAG = "barcode";
	
	public static final String COMPANY_TAG = "company";
		
	public static final String TAG = BarcodeService.class.getSimpleName();

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		handleCommand(intent);
		return START_STICKY;
	}

	private void handleCommand(Intent intent) {
		if (intent == null) {
			return;
		}

		String barcode = intent.getStringExtra(BARCODE_TAG);

		ContentManager.getInstance().getCompanyNameByBarcode(BarcodeService.this, barcode, this);
	}

	@Override
	public void onSuccess(String p) {
		Intent intent = new Intent(ACTION_ON_SUCCESS);
		intent.putExtra(COMPANY_TAG, p);
		sendBroadcast(intent);
	}

	@Override
	public void onError(Throwable e) {
		Intent intent = new Intent(ACTION_ON_ERROR);
		intent.putExtra(EXTRA_KEY_MESSAGE, e.getMessage());
		sendBroadcast(intent);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

}
